package com.qmscy.sparrow.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * md5 加密工具
 *
 * @Author: wangxiaonan
 * @Date: 2019/1/2
 **/
public class MD5Util {
    private static final Logger logger = LoggerFactory.getLogger(MD5Util.class);

    private static MessageDigest messageDigest;
    private static char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    static {
        try {
            messageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            logger.error("[NoSuchAlgorithmException] MD5 instance fail!", e);
        }
    }

    public static String MD5_16bit(String input) {
        String hash = MD5_32bit(input);
        if (hash == null) {
            return null;
        }
        return hash.substring(8, 24);
    }

    public static String MD5_32bit(String input) {
        if (input == null || input.length() == 0) {
            return null;
        }
        messageDigest.update(input.getBytes());
        byte[] digest = messageDigest.digest();
        return convertToString(digest);
    }

    private static String convertToString(byte[] data) {
        StringBuilder r = new StringBuilder(data.length * 2);
        for (byte b : data) {
            r.append(hexDigits[(b >> 4) & 0xF]);
            r.append(hexDigits[(b & 0xF)]);
        }
        return r.toString();
    }
}
